<template>
  <div class="login-container">
    <van-nav-bar
      class="app-nav-bar"
      title="注册 / 登录"
      left-arrow
      @click-left="$router.back()" />
    <van-form
      :show-error="false"
      :show-error-message="false"
      validate-first
      ref="login-form"
      @submit="onLogin"
      @failed="onFailed" >
      <van-field
        v-model="user.username"
        left-icon="manager-o"
        center
        placeholder="请输入手机号"
        name="username"
        :rules="formRules.username" />
      <van-field
        v-model="user.password"
        clearable
        left-icon="chat-o"
        center
        placeholder="请输入密码"
        name="password"
        :rules="formRules.password" />
      <div class="login-btn-wrap">
        <van-button class="login-btn" type="info" block>登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
export default {
  components: {},
  props: {},
  data () {
    return {
      user: {
        username: '17347315273',
        password: '9527'
      },
      formRules: {
        username: [
          { required: true, message: '请输入手机号' },
          { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '手机号格式错误' }
        ],
        password: [
          { required: true, message: '请输入密码' },
          { pattern: /^\d{4}$/, message: '密码格式错误' }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    async onLogin () {
      this.$toast.loading({
        message: '登录中...',
        forbidClick: true,
        duration: 0
      })
      await this.$http.post('api/user/login', {
        data: {
          username: this.user.username,
          password: this.user.password
        }
      }).then(({ data: res }) => {
        if (res.code === 0) {
          this.$toast.success('登录成功')
          this.$store.commit('setUser', { ...res.data, photo: process.env.VUE_APP_API_BASE_URL + res.data.photo })
          Cookies.set('token', res.token)
          this.$router.push(this.$route.query.redirect || '/')
        } else if (res.code === 2) {
          this.$toast.success(res.msg)
        } else {
          this.$toast.fail('登录失败，密码或网咯错误')
        }
      })
    },

    onFailed (error) {
      if (error.errors[0]) {
        this.$toast({
          message: error.errors[0].message,
          position: 'top'
        })
      }
    }

  }
}
</script>

<style scoped lang="less">
.login-container {
  .send-btn {
    width: 76px;
    height: 23px;
    background-color: #ededed;
    .van-button__text {
      font-size: 11px;
      color: #666666;
    }
  }
  .login-btn-wrap {
    padding: 26px 16px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
      .van-button__text {
        font-size: 15px;
      }
    }
  }
}
</style>
